<script setup>
import { ref, onMounted } from "vue";
import {
  queryPageApi,
  addRoleApi,
  updateRoleApi,
  deleteRoleApi,
  getRoleByIdApi,
} from "@/api/role";
import { ElMessage, ElMessageBox } from "element-plus";

// 查询参数
const queryParams = ref({
  name: "",
  label: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const roleList = ref([]);
const total = ref(0);

onMounted(() => {
  search();
});

// 查询按钮
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code == 1) {
    roleList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 重置查询
const clear = () => {
  queryParams.value = {
    name: "",
    label: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val;
  search();
};

// 表单校验
const roleFormRef = ref();
const rules = ref({
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  label: [
    { required: true, message: "请输入角色标识", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择角色状态", trigger: "change" }],
});

// 新增/修改角色对话框
const dialog = ref({
  title: "",
  visible: false,
});

const roleForm = ref({
  name: "",
  label: "",
  status: 1,
  remark: "",
});

// 添加角色按钮
const handleAdd = () => {
  dialog.value.title = "添加角色";
  dialog.value.visible = true;
  roleForm.value = {
    name: "",
    label: "",
    status: 1,
    remark: "",
  };
};

// 修改角色按钮
const handleEdit = async (id) => {
  try {
    const result = await getRoleByIdApi(id);
    if (result.code == 1) {
      roleForm.value = { ...result.data };
      dialog.value.title = "修改角色";
      dialog.value.visible = true;
    } else {
      ElMessage.error(result.msg);
    }
  } catch (error) {
    ElMessage.error("获取角色信息失败");
  }
};

// 保存按钮
const save = async () => {
  roleFormRef.value.validate(async (valid) => {
    if (!valid) return;

    try {
      let result;
      if (roleForm.value.id) {
        // 修改
        result = await updateRoleApi(roleForm.value);
      } else {
        // 添加
        result = await addRoleApi(roleForm.value);
      }

      if (result.code == 1) {
        dialog.value.visible = false;
        ElMessage.success(roleForm.value.id ? "修改成功" : "添加成功");
        search();
      } else {
        ElMessage.error(result.msg);
      }
    } catch (error) {
      ElMessage.error("操作失败");
    }
  });
};

// 删除角色
const deleteRole = async (id) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const result = await deleteRoleApi(id);
        if (result.code == 1) {
          ElMessage.success("删除成功");
          search();
        } else {
          ElMessage.error(result.msg);
        }
      } catch (error) {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

<template>
  <div class="role">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="角色名称:">
        <el-input v-model="queryParams.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色标识:">
        <el-input v-model="queryParams.label" placeholder="请输入角色标识" />
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button @click="clear"
          ><el-icon><Refresh /></el-icon>清空</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd"
        ><el-icon><Plus /></el-icon>添加角色</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table :data="roleList" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column
        prop="name"
        label="角色名称"
        width="300"
        align="center"
      />
      <el-table-column
        prop="label"
        label="角色标识"
        width="300"
        align="center"
      />
      <el-table-column
        prop="updateTime"
        label="最后修改时间"
        width="300"
        align="center"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)"
            ><el-icon><Edit /></el-icon>修改</el-button
          >
          <el-button type="danger" link @click="deleteRole(scope.row.id)"
            ><el-icon><Delete /></el-icon>删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/修改角色对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      class="role-dialog"
    >
      <el-form
        :model="roleForm"
        ref="roleFormRef"
        :rules="rules"
        label-width="80px"
        class="role-form"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="label">
          <el-input v-model="roleForm.label" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="roleForm.status"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false"
          ><el-icon><Close /></el-icon>取消</el-button
        >
        <el-button type="primary" @click="save"
          ><el-icon><Check /></el-icon>确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.role {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px; /* 添加圆角 */
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 280px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.divider {
  height: 0.5px;
  background-color: #dcdfe6;
  margin: 10px 0;
  width: 100%;
}

:deep(.role-dialog .el-dialog__body) {
  padding-top: 30px;
}

.role-form {
  width: 80%;
  margin: 0 auto;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}
</style>
